package CarRental;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JButton exitButton; // 新增退出按钮
    private JLabel roleLabel;
    private JComboBox<String> roleComboBox;

    public LoginFrame() {
        // 设置窗口标题
        setTitle("汽车租赁系统登录");
        // 设置窗口大小为 600x500
        setSize(600, 500);
        // 设置关闭窗口时退出程序
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口居中显示
        setLocationRelativeTo(null);

        // 设置全局字体大小
        Font largerFont = new Font("SansSerif", Font.PLAIN, 18);
        UIManager.put("Label.font", largerFont);
        UIManager.put("TextField.font", largerFont);
        UIManager.put("PasswordField.font", largerFont);
        UIManager.put("ComboBox.font", largerFont);
        UIManager.put("Button.font", largerFont);

        // 设置按钮背景颜色为黄色
        UIManager.put("Button.background", Color.YELLOW);

        // 创建面板并设置布局为 6 行 2 列的网格布局
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10); // 设置组件之间的间距

        // 创建用户名标签和输入框
        JLabel usernameLabel = new JLabel("用户名:");
        usernameField = new JTextField();
        // 创建密码标签和输入框
        JLabel passwordLabel = new JLabel("密码:");
        passwordField = new JPasswordField();
        // 创建角色标签和下拉框
        roleLabel = new JLabel("角色:");
        roleComboBox = new JComboBox<>(new String[]{"Admin", "VIP"});
        // 创建登录按钮
        loginButton = new JButton("登录");
        // 创建注册按钮
        registerButton = new JButton("注册");
        // 创建退出按钮
        exitButton = new JButton("退出程序");

        // 将组件添加到面板中
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(usernameLabel, gbc);
        gbc.gridx = 1;
        panel.add(usernameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(passwordLabel, gbc);
        gbc.gridx = 1;
        panel.add(passwordField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(roleLabel, gbc);
        gbc.gridx = 1;
        panel.add(roleComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(loginButton, gbc);

        gbc.gridy = 4;
        panel.add(registerButton, gbc);

        gbc.gridy = 5;
        panel.add(exitButton, gbc);

        // 为登录按钮添加事件监听器
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取用户输入的用户名、密码和角色
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                String role = (String) roleComboBox.getSelectedItem();

                // 调用 authenticate 方法进行用户认证
                int userId = authenticate(username, password, role);
                if (userId != -1) {
                    // 根据角色跳转到不同的界面
                    if (role.equals("Admin")) {
                        new AdminFrame().setVisible(true);
                    } else {
                        new UserFrame(userId).setVisible(true); // 传递当前登录用户的 UserID
                    }
                    dispose(); // 关闭当前窗口
                } else {
                    // 显示错误消息
                    JOptionPane.showMessageDialog(LoginFrame.this, "用户名或密码错误");
                }
            }
        });

        // 为注册按钮添加事件监听器
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 调用 registerUser 方法进行用户注册
                registerUser();
            }
        });

        // 为退出按钮添加事件监听器
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 退出程序
                System.exit(0);
            }
        });

        // 将面板添加到窗口中
        add(panel);
    }

    // 用户认证方法
    private int authenticate(String username, String password, String role) {
        // SQL 查询语句，根据用户名、密码和角色查找用户
        String sql = "SELECT UserID FROM Users WHERE Username = ? AND Password = ? AND Role = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 设置 SQL 查询参数
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, role);
            // 执行查询
            ResultSet rs = pstmt.executeQuery();

            // 如果查询结果有数据，返回 UserID
            if (rs.next()) {
                return rs.getInt("UserID"); // 返回当前登录用户的 UserID
            }
        } catch (SQLException e) {
            // 捕获并打印 SQL 异常
            e.printStackTrace();
        }
        return -1; // 认证失败
    }

    // 用户注册方法
    private void registerUser() {
        // 弹出输入对话框，获取用户输入的用户名、密码、联系电话和邮箱
        String username = JOptionPane.showInputDialog("请输入用户名:");
        String password = JOptionPane.showInputDialog("请输入密码:");
        String role = "VIP"; // 默认注册为 VIP 用户
        String phoneNumber = JOptionPane.showInputDialog("请输入联系电话:");
        String email = JOptionPane.showInputDialog("请输入邮箱:");

        // SQL 插入语句，将新用户信息插入到数据库中
        String sql = "INSERT INTO Users (Username, Password, Role, PhoneNumber, Email) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 设置 SQL 插入参数
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, role);
            pstmt.setString(4, phoneNumber);
            pstmt.setString(5, email);
            // 执行插入操作
            pstmt.executeUpdate();

            // 显示注册成功消息
            JOptionPane.showMessageDialog(this, "注册成功！");
        } catch (SQLException e) {
            // 捕获并打印 SQL 异常，并显示注册失败消息
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "注册失败: " + e.getMessage());
        }
    }

    // 主方法，程序入口
    public static void main(String[] args) {
        // 创建并显示登录窗口
        new LoginFrame().setVisible(true);
    }
}
